const fileService = require('../services/file.service')
const userService = require('../services/user.service')
const { APP_HOST,	APP_PORT } = require('../app/config')

class FileController {
  async saveAvatarInfo(ctx, next) {
    // 获取头像图片相关信息
    const {id} = ctx.user
    // @koa/multer: ctx.request.file
    // koa-multer: ctx.req.file
    const {filename, mimetype, size} = ctx.request.file

    try {
      // 将头像图片信息插入 avatar 数据表中
      await fileService.createAvatar(filename, mimetype, size, id)

      // 构建头像图片URL地址（对应【获取用户头像接口】）
      const avatarUrl = `${APP_HOST}:${APP_PORT}/user/${id}/avatar`
      // console.log(`avatarUrl: ---`, avatarUrl);

      // 将头像图片URL地址更新到 user 表中
      await userService.updateAvatarUrlByUserId(avatarUrl, id)

      ctx.body = '头像图片上传成功~'
    } catch (error) {
      console.log(`error: ${error.message}`);
    }
    
  }

  async savePictureInfo(ctx, next) {
    const {id} = ctx.user
    const {momentId} = ctx.request.query
    const {files} = ctx.request

    for(let file of files) {
      const {filename, mimetype, size} = file
      try {
        await fileService.createFile(filename, mimetype, size, momentId, id)
      } catch (error) {
        console.log(`error: ${error.message}`);
      }
      
    }

    ctx.body = `上传动态配图成功~`
  }
}

module.exports = new FileController()